package com.example.wwww.controller;

import com.example.wwww.model.Order;
import com.example.wwww.repo.InMemoryStore;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/orders")
public class OrderController {
    private final InMemoryStore store;
    public OrderController(InMemoryStore store) { this.store = store; }

    @GetMapping
    public List<Order> list(@RequestParam(required = false) Long userId,
                            @RequestParam(required = false) Long merchantId,
                            @RequestParam(required = false) Long riderId,
                            @RequestParam(required = false) String riderStatus,
                            @RequestParam(required = false) String status) {
        List<Order> base = store.getOrders();
        return base.stream()
                .filter(o -> userId == null || userId.equals(o.getUserId()))
                .filter(o -> merchantId == null || merchantId.equals(o.getMerchantId()))
                .filter(o -> riderId == null || riderId.equals(o.getRiderId()))
                .filter(o -> riderStatus == null || riderStatus.equals(o.getRiderStatus()))
                .filter(o -> status == null || status.equals(o.getStatus()))
                .toList();
    }

    @GetMapping("/available")
    public List<Order> available() { return store.getAvailableOrders(); }

    @GetMapping("/{id}")
    public ResponseEntity<Order> get(@PathVariable Long id) {
        return store.getOrderById(id).map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public Order create(@RequestBody Order order) { return store.addOrder(order); }

    @PatchMapping("/{id}")
    public ResponseEntity<Order> patch(@PathVariable Long id, @RequestBody Map<String, Object> updates) {
        Order up = new Order();
        if (updates.containsKey("status")) up.setStatus((String) updates.get("status"));
        if (updates.containsKey("riderStatus")) up.setRiderStatus((String) updates.get("riderStatus"));
        if (updates.containsKey("riderId")) up.setRiderId(Long.valueOf(String.valueOf(updates.get("riderId"))));
        if (updates.containsKey("estimatedTime")) up.setEstimatedTime(Integer.valueOf(String.valueOf(updates.get("estimatedTime"))));
        Order updated = store.updateOrder(id, up);
        return updated == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(updated);
    }
}


